<template>
  <div class="hospital-layout">
    <!-- 头部导航 -->
    <header class="header">
      <div class="header-left">
        <h1 class="logo">智慧医院管理系统</h1>
      </div>
      <div class="header-right">
        <div class="user-info">
          <span class="user-name">欢迎您，{{ staffName }}</span>
          <button class="logout-btn" @click="handleLogout">退出</button>
        </div>
      </div>
    </header>

    <!-- 主体区域 -->
    <div class="main-container">
      <!-- 侧边栏 -->
      <aside class="sidebar">
        <div class="menu-title">门诊模块</div>
        <ul class="menu-list">
          <li class="menu-item" :class="{ active: activeMenu === 'outpatient' }" @click="selectMenu('outpatient')">
            <span class="menu-icon">🏥</span>
            <span class="menu-text">门诊管理</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'registration' }" @click="selectMenu('registration')">
            <span class="menu-icon">📋</span>
            <span class="menu-text">挂号管理</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'patient' }" @click="selectMenu('patient')">
            <span class="menu-icon">👤</span>
            <span class="menu-text">患者详情</span>
          </li>
        </ul>

        <div class="menu-title">住院模块</div>
        <ul class="menu-list">
          <li class="menu-item" :class="{ active: activeMenu === 'ward-doctor' }" @click="selectMenu('ward-doctor')">
            <span class="menu-icon">👨‍⚕️</span>
            <span class="menu-text">医生站</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'ward-nurse' }" @click="selectMenu('ward-nurse')">
            <span class="menu-icon">👩‍⚕️</span>
            <span class="menu-text">护士站</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'inpatient-apply' }" @click="selectMenu('inpatient-apply')">
            <span class="menu-icon">📄</span>
            <span class="menu-text">护士站-入院申请列表</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'discharge-apply' }" @click="selectMenu('discharge-apply')">
            <span class="menu-icon">📤</span>
            <span class="menu-text">护士站-出院申请列表</span>
          </li>
        </ul>

        <div class="menu-title">管理模块</div>
        <ul class="menu-list">
          <li class="menu-item" :class="{ active: activeMenu === 'billing' }" @click="selectMenu('billing')">
            <span class="menu-icon">💰</span>
            <span class="menu-text">收费站</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'pharmacy' }" @click="selectMenu('pharmacy')">
            <span class="menu-icon">💊</span>
            <span class="menu-text">药品管理</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'staffView' }" @click="selectMenu('staffView')">
            <span class="menu-icon">👥</span>
            <span class="menu-text">人事管理</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'permission' }" @click="selectMenu('permission')">
            <span class="menu-icon">🛡️</span>
            <span class="menu-text">权限分配</span>
          </li>
<!--          <li class="menu-item" :class="{ active: activeMenu === 'assets' }" @click="selectMenu('assets')">-->
<!--            <span class="menu-icon">🏢</span>-->
<!--            <span class="menu-text">固定资产管理</span>-->
<!--          </li>-->
          <li class="menu-item" :class="{ active: activeMenu === 'wardView' }" @click="selectMenu('wardView')">
            <span class="menu-icon">🛏️</span>
            <span class="menu-text">病房管理</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'equipment' }" @click="selectMenu('equipment')">
            <span class="menu-icon">🔧</span>
            <span class="menu-text">设备管理</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'examItem' }" @click="selectMenu('examItem')">
            <span class="menu-icon">📋</span>
            <span class="menu-text">检查项目管理</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'surgeryItem' }" @click="selectMenu('surgeryItem')">
            <span class="menu-icon">🔪</span>
            <span class="menu-text">手术项目管理</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'patientExam' }" @click="selectMenu('patientExam')">
            <span class="menu-icon">📊</span>
            <span class="menu-text">患者检查详情</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'patientSurgery' }" @click="selectMenu('patientSurgery')">
            <span class="menu-icon">⚔️</span>
            <span class="menu-text">患者手术详情</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'employees' }" @click="selectMenu('employees')">
            <span class="menu-icon">🏢</span>
            <span class="menu-text">员工请假</span>
          </li>
          <li class="menu-item" :class="{ active: activeMenu === 'timeSlot' }" @click="selectMenu('timeSlot')">
            <span class="menu-icon">🏢</span>
            <span class="menu-text">排班表</span>
          </li>
        </ul>
      </aside>

      <!-- 内容区域 -->
      <main class="content">

        <div class="content-header">
          <h2>{{ menuTitles[activeMenu] || '首页' }}</h2>
          <div class="breadcrumb">
            <span>首页</span> >
            <span>{{ menuTitles[activeMenu] || '首页' }}</span>
          </div>
        </div>
        <div class="content-body">
<!--           根据选中的菜单显示不同内容-->
          <div v-if="activeMenu === 'outpatient'" class="module-content">
            <router-view></router-view>
          </div>

          <div v-else-if="activeMenu === 'registration'" class="module-content">
            <h3>挂号管理模块</h3>
            <p>这里是挂号管理的相关功能和数据展示</p>
            <div class="stats">
              <div class="stat-card">
                <h4>今日挂号数</h4>
                <p class="stat-number">96</p>
              </div>
              <div class="stat-card">
                <h4>已预约</h4>
                <p class="stat-number">32</p>
              </div>
              <div class="stat-card">
                <h4>现场挂号</h4>
                <p class="stat-number">64</p>
              </div>
            </div>
          </div>
          <div v-else-if="activeMenu === 'patient'" class="module-content">
            <h3>患者详情管理</h3>
            <p>这里是患者信息管理的相关功能和数据展示</p>
            <div class="stats">
              <div class="stat-card">
                <h4>总患者数</h4>
                <p class="stat-number">1,248</p>
              </div>
              <div class="stat-card">
                <h4>今日新增</h4>
                <p class="stat-number">18</p>
              </div>
              <div class="stat-card">
                <h4>活跃患者</h4>
                <p class="stat-number">892</p>
              </div>
            </div>
          </div>
          <div v-else-if="activeMenu === 'ward-doctor'" class="module-content">
            <router-view/>
          </div>
          <div v-else-if="activeMenu === 'ward-nurse'" class="module-content">
            <router-view></router-view>
          </div>
          <div v-else-if="activeMenu === 'inpatient-apply'" class="module-content">
            <router-view></router-view>
          </div>
          <div v-else-if="activeMenu === 'discharge-apply'" class="module-content">
            <router-view></router-view>
          </div>

          <div v-else-if="activeMenu === 'billing'" class="module-content">
            <router-view></router-view>
          </div>

          <div v-else-if="activeMenu === 'pharmacy'" class="module-content">
            <router-view></router-view>
          </div>
          <div v-else-if="activeMenu === 'employees'" class="module-content">
            <router-view></router-view>
          </div>

          <div v-else-if="activeMenu === 'staffView'" class="module-content">
            <router-view></router-view>
<!--            <h3>人事管理模块</h3>-->
<!--            <p>这里是人事管理的相关功能和数据展示</p>-->
<!--            <div class="stats">-->
<!--              <div class="stat-card">-->
<!--                <h4>员工总数</h4>-->
<!--                <p class="stat-number">286</p>-->
<!--              </div>-->
<!--              <div class="stat-card">-->
<!--                <h4>今日考勤</h4>-->
<!--                <p class="stat-number">284</p>-->
<!--              </div>-->
<!--              <div class="stat-card">-->
<!--                <h4>请假申请</h4>-->
<!--                <p class="stat-number">5</p>-->
<!--              </div>-->
<!--            </div>-->
          </div>
          <div v-else-if="activeMenu === 'assets'" class="module-content">
            <h3>固定资产管理模块</h3>
            <p>这里是固定资产管理的相关功能和数据展示</p>
            <div class="stats">
              <div class="stat-card">
                <h4>资产总数</h4>
                <p class="stat-number">1,204</p>
              </div>
              <div class="stat-card">
                <h4>本月折旧</h4>
                <p class="stat-number">¥12,450</p>
              </div>
              <div class="stat-card">
                <h4>维修中</h4>
                <p class="stat-number">12</p>
              </div>
            </div>
          </div>

          <div v-else-if="activeMenu === 'permission'" class="module-content">
            <router-view></router-view>
          </div>

          <div v-else-if="activeMenu === 'wardView'" class="module-content">
            <router-view></router-view>
          </div>
          <div v-else-if="activeMenu === 'equipment'" class="module-content">
            <router-view></router-view>
          </div>
          <div v-else-if="activeMenu === 'examItem'" class="module-content">
            <router-view></router-view>
          </div>
          <div v-else-if="activeMenu === 'surgeryItem'" class="module-content">
            <router-view></router-view>
          </div>
          <div v-else-if="activeMenu === 'patientSurgery'" class="module-content">
            <router-view></router-view>
          </div>
          <div v-else-if="activeMenu === 'patientExam'" class="module-content">
            <router-view></router-view>
          </div>
          <div v-else-if="activeMenu === 'timeSlot'" class="module-content">
            <router-view></router-view>
          </div>


          <div v-else class="welcome-content">
            <h3>欢迎使用智慧医院管理系统</h3>
            <p>请选择左侧菜单功能模块开始操作</p>
            <div class="dashboard-overview">
              <div class="overview-card">
                <h4>总床位数</h4>
                <p class="overview-number">320</p>
              </div>
              <div class="overview-card">
                <h4>门诊科室</h4>
                <p class="overview-number">24</p>
              </div>
              <div class="overview-card">
                <h4>医护人员</h4>
                <p class="overview-number">456</p>
              </div>
              <div class="overview-card">
                <h4>月收入</h4>
                <p class="overview-number">¥2.4M</p>
              </div>
            </div>
          </div>
        </div>
<!--        <router-view></router-view>-->

      </main>
    </div>
  </div>
</template>

<script>
import { ElNotification } from 'element-plus';
import {jwtDecode} from "jwt-decode";
export default {
  name: 'HospitalLayout',
  data() {
    return {
      staffName: '',
      activeMenu: '',
      menuTitles: {
        'outpatient': '门诊管理',
        'registration': '挂号管理',
        'patient': '患者详情管理',
        'ward-doctor': '住院部医生站',
        'ward-nurse': '住院部护士站',
        'inpatient-apply': '入院申请列表',
        'discharge-apply': '出院申请列表',
        'billing': '收费站模块',
        'pharmacy': '药品管理',
        'hr': '人事管理',
        'assets': '固定资产管理',
        'employees':'员工管理',
        'wardView': '病房管理',
        'equipment': '设备管理',
        'examItem': '检查项目管理',
        'surgeryItem': '手术项目管理',
        'permission': '权限分配',
        'patientSurgery': '患者手术详情',
        'patientExam': '患者检查详情',
        'timeSlot': '排班表'

      },
      // 添加 socket 实例
      socket: null,
      staffId: null
    }
  },
  created() {
    this.getStaffInfo();
    this.initWebSocket();
  },
  methods: {
    selectMenu(menu) {
      this.activeMenu = menu;
      if (menu === 'outpatient') {
        this.$router.push('/outPatient');
      }else if (menu === 'registration') {
        this.$router.push('/registration');
      }else if (menu === 'patient') {
        this.$router.push('/patient');
      }else if (menu === 'ward-doctor') {
        this.$router.push('/ward-doctor');
      }else if (menu === 'ward-nurse') {
        this.$router.push('/wardNurse');
      }else if (menu === 'inpatient-apply') {
        this.$router.push('/inpatient-apply');
      }else if (menu === 'discharge-apply') {
        this.$router.push('/discharge-apply');
      }else if (menu === 'billing') {
        this.$router.push('/billing');
      }else if (menu === 'pharmacy') {
        this.$router.push('/pharmacy');
      }else if (menu === 'staffView') {
        this.$router.push('/staffView');
      }else if (menu === 'wardView') {
        this.$router.push('/wardView');
      }else if (menu === 'equipment') {
        this.$router.push('/equipment');
      }else if (menu === 'examItem') {
        this.$router.push('/examItem');
      }else if (menu === 'surgeryItem') {
        this.$router.push('/surgeryItem');
      }else if (menu === 'permission') {
        this.$router.push('/permission');
      }else if (menu === 'patientSurgery') {
        this.$router.push('/patientSurgery');
      }else if(menu==='employees'){
        this.$router.push('/employees');
      }else if(menu==='patientExam'){
        this.$router.push('/patientExam');
      }else if(menu==='timeSlot'){
        this.$router.push('/timeSlot');
      }
    },
    handleLogout() {
      sessionStorage.removeItem('staffInfo');
      sessionStorage.removeItem('token');
      this.$router.push('/login');
      // alert('退出登录功能待实现');
      // 实际项目中这里会调用登出API
    },
    parseJwt(token) {
      try {
        const base64Url = token.split('.')[1];
        const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
        const jsonPayload = decodeURIComponent(atob(base64).split('').map(function(c) {
          return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
        }).join(''));
        return JSON.parse(jsonPayload);
      } catch (error) {
        console.error('解析token失败:', error);
        return null;
      }
    },
    getStaffInfo() {
      // console.log('开始获取员工信息');
      const staffInfo = sessionStorage.getItem('staffInfo');
      const token = sessionStorage.getItem('token');
      // console.log('sessionStorage中的staffInfo:', staffInfo);
      // console.log('sessionStorage中的token:', token);
      if (staffInfo) {
        const staff = JSON.parse(staffInfo);
        this.staffName = staff.name;
      }
      if (token) {
        const tokenData = this.parseJwt(token);
        if (tokenData && tokenData.staff) {
          this.staffName = tokenData.staff.name;
          // console.log('从token获取到姓名:', this.staffName);

          // 同时保存到sessionStorage，方便下次使用
          sessionStorage.setItem('staffInfo', JSON.stringify(tokenData.staff));
        }
      }
    },

    //  额外添加的 WebSocket 方法
    initWebSocket() {
      // ** 关键 **
      // 您必须在用户登录时，将 staffId 存入 localStorage
      // (例如：localStorage.setItem('staffId', 123))
      let token = sessionStorage.getItem('token');
      const decoded = jwtDecode(token)
      this.staffId = decoded.id

      if (!this.staffId) {
        console.error("无法初始化WebSocket：未在 localStorage 中找到 staffId。");
        return;
      }

      // (这个 /ws/notify/{staffId} 对应我们新建的 @ServerEndpoint)
      const wsUrl = `ws://localhost:8080/ws/notify/${this.staffId}`;

      try {
        this.socket = new WebSocket(wsUrl);

        this.socket.onopen = () => {
          console.log(`WebSocket 通知服务已连接 (用户: ${this.staffId})。`);
        };

        this.socket.onmessage = (event) => {
          console.log("收到WebSocket通知:", event.data);
          try {
            const payload = JSON.parse(event.data);

            // (检查消息类型是否为我们定义的)
            if (payload.type === 'ADMISSION_REJECTED') {
              ElNotification({
                title: payload.title || '系统通知',
                message: payload.message,
                type: 'warning',
                duration: 10000 // 持续10秒
              });
            }
          } catch (e) {
            console.error("无法解析WebSocket消息:", e);
          }
        };

        this.socket.onclose = () => {
          console.log("WebSocket 通知服务已断开。");
          this.socket = null;
        };

        this.socket.onerror = (error) => {
          console.error("WebSocket 发生错误:", error);
        };

      } catch (error) {
        console.error("WebSocket 初始化失败:", error);
      }
    },

    closeWebSocket() {
      if (this.socket) {
        this.socket.close();
      }
    }
  },
  //  在 created 钩子中初始化


  //  在 beforeUnmount 钩子中销毁
  beforeUnmount() {
    this.closeWebSocket();
  }
}
</script>

<style scoped>
.hospital-layout {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.header {
  height: 60px;
  background: linear-gradient(135deg, #1a6dcc, #0d47a1);
  color: white;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  z-index: 100;
}

.header-left {
  flex: 1;
  display: flex;
  justify-content: center;
}

.logo {
  font-size: 1.5rem;
  font-weight: bold;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-name {
  font-size: 0.9rem;
}

.logout-btn {
  background: rgba(255,255,255,0.2);
  border: 1px solid rgba(255,255,255,0.3);
  color: white;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
}

.logout-btn:hover {
  background: rgba(255,255,255,0.3);
}

.main-container {
  display: flex;
  flex: 1;
  overflow: hidden;
}

.sidebar {
  width: 240px;
  background: white;
  border-right: 1px solid #e0e0e0;
  overflow-y: auto;
  padding: 20px 0;
}

.menu-title {
  padding: 10px 20px;
  font-size: 0.8rem;
  text-transform: uppercase;
  color: #666;
  background: #f8f9fa;
  border-left: 3px solid #1a6dcc;
}

.menu-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.menu-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.3s;
  border-left: 3px solid transparent;
}

.menu-item:hover {
  background: #e3f2fd;
}

.menu-item.active {
  background: #e3f2fd;
  border-left: 3px solid #1a6dcc;
  color: #1a6dcc;
  font-weight: bold;
}

.menu-icon {
  margin-right: 10px;
  font-size: 1.1rem;
}

.menu-text {
  font-size: 0.95rem;
}

.content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

.content-header {
  margin-bottom: 20px;
}

.content-header h2 {
  color: #333;
  margin-bottom: 5px;
}

.breadcrumb {
  color: #666;
  font-size: 0.9rem;
}

.content-body {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.05);
}

.module-content, .welcome-content {
  padding: 20px 0;
}

.stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 20px;
}

.stat-card, .overview-card {
  background: #f8f9fa;
  border-radius: 8px;
  padding: 15px;
  text-align: center;
  border: 1px solid #e9ecef;
}

.stat-card h4, .overview-card h4 {
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 5px;
}

.stat-number, .overview-number {
  font-size: 1.5rem;
  font-weight: bold;
  color: #1a6dcc;
}

.welcome-content {
  text-align: center;
}

.welcome-content h3 {
  color: #333;
  margin-bottom: 10px;
}

.dashboard-overview {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-top: 30px;
}
</style>



